package rpc.simple.impl.tag3;

import rpc.simple.impl.exception.SimpleRpcFrameworkException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * XXX
 *
 * @author mengzhang6
 * @date 2019/1/3 9:40
 */
public class ProviderRunnable implements Runnable {

    private Socket socket;
    private Object service;

    private ProviderRunnable(Socket socket, Object service) {
        this.socket = socket;
        this.service = service;
    }

    public static ProviderRunnable newInstice(Socket socket, Object service) {
        if (socket == null) {
            throw new SimpleRpcFrameworkException("此接收的请求异常");
        }
        return new ProviderRunnable(socket, service);
    }

    @Override
    public void run() {

        try (
                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
        ) {
            String methodName = input.readUTF();
            Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
            Object[] arguments = (Object[]) input.readObject();
            Method method = service.getClass().getMethod(methodName, parameterTypes);
            Object result = method.invoke(service, arguments);
            output.writeObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
